from django.utils.safestring import mark_safe
import copy

"""
自定义的分页组件，以后如果想要使用这个分页组件，只需要
在视图函数中，调用这个分页组件即可，代码如下：
from app01.utils.pageination import Pagination
def pretty_list(request):
    1.根据自己的需求去筛选数据
    queryset = models.PrettyMum.objects.all()
    2.实例化分页对象
    page_object = Pagination(request, queryset)

    context = {
        'queryset': page_object.page_queryset,  # 分页之后的数据
        'page_str': page_object.html()          # 页码html
    }
    return render(request, 'pretty_list.html', context)
    
在html中：
    {% for obj in queryset %}
        {{ obj.xx }}
    {% endfor %}
    <ul class="pagination" style="float: left">
        {{ page_str }}
    </ul>
"""


class Pagination(object):
    def __init__(self, request, queryset, page_size=10, page_param='page', plus=5):
        """
        :param request: 请求对象
        :param queryset: 符合条件的数据(根据这个数据进行分页)
        :param page_size: 每页显示多少条数据
        :param page_param: 在url中传递的获取页码的参数。例如：/pretty/list/?page=7
        :param plus: 显示当前页的前五页和后五页
        """
        query_dict = copy.deepcopy(request.GET)
        query_dict._mutable = True
        self.query_dict = query_dict
        self.page_param = page_param
        page = request.GET.get(page_param, '1')
        if page.isdecimal():
            self.page = int(page)
        else:
            self.page = 1
        self.page_size = page_size
        self.start = (self.page - 1) * self.page_size  # 计算起始页码
        self.end = self.start + self.page_size  # 计算结束页码

        total_count = queryset.count()
        total_page_count, div = divmod(total_count, self.page_size)
        if div:
            total_page_count += 1
        self.total_page_count = total_page_count
        # 计算出显示当前页的前五页和后五页
        self.plus = plus
        self.page_queryset = queryset[self.start:self.end]  # 降序排列

    def html(self):
        if self.total_page_count <= 2 * self.plus + 1:
            # 数据库的数据比较少，都没有达到11页
            start_page = 1
            end_page = self.total_page_count
        else:
            # 数据库的数据比较多，超过了11页
            if self.page <= self.plus:
                start_page = 1
                end_page = 2 * self.plus
            else:
                # 当前页大于5页，当前页+5页大于总页数
                if (self.page + self.plus) > self.total_page_count:
                    start_page = self.total_page_count - 2 * self.plus
                    end_page = self.total_page_count
                else:
                    start_page = self.page - self.plus
                    end_page = self.page + self.plus

        # 页码
        page_str_list = []
        # 首页
        self.query_dict.setlist(self.page_param, [1])
        first = '<li><a href="?{}" aria-label="Next"><span aria-hidden="true">首页</span></a></li>'.format(
            self.query_dict.urlencode())
        page_str_list.append(first)
        if self.page > 1:  # 第一页
            self.query_dict.setlist(self.page_param, [self.page - 1])
            prev = '<li><a href="?{}" aria-label="Next"><span aria-hidden="true">«</span></a></li>'.format(
                self.query_dict.urlencode())
        else:
            self.query_dict.setlist(self.page_param, [1])
            prev = '<li><a href="?{}" aria-label="Next"><span aria-hidden="true">«</span></a></li>'.format(
                self.query_dict.urlencode())
        page_str_list.append(prev)

        for i in range(start_page, end_page + 1):
            self.query_dict.setlist(self.page_param, [i])
            if i == self.page:
                ele = '<li class="active"><a href="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
            else:
                ele = '<li><a href="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
            page_str_list.append(ele)

        if self.page < self.total_page_count:  # 最后一页
            self.query_dict.setlist(self.page_param, [self.page + 1])
            next = '<li><a href="?{}" aria-label="Next"><span aria-hidden="true">»</span></a></li>'.format(
                self.query_dict.urlencode())
        else:
            self.query_dict.setlist(self.page_param, [self.total_page_count])
            next = '<li><a href="?{}" aria-label="Next"><span aria-hidden="true">»</span></a></li>'.format(
                self.query_dict.urlencode())
        page_str_list.append(next)
        # 尾页
        self.query_dict.setlist(self.page_param, [self.total_page_count])
        last = '<li><a href="?{}" aria-label="Next"><span aria-hidden="true">尾页</span></a></li>'.format(
            self.query_dict.urlencode())
        page_str_list.append(last)
        search_str = """
        <li>
            <form style="float: left;margin-right: -1px" method="get">
                <input name="page"
                       style="position: relative;float: left;display: inline-block;width: 80px;border-radius: 0"
                       type="text" class="form-control" placeholder="页码">
                <button style="border-radius: 0" class="btn btn-default" type="submit">跳转</button>
            </form>
        </li>
        """
        page_str_list.append(search_str)
        page_str = mark_safe(''.join(page_str_list))
        return page_str
